<template>
    <div style="position:relative;height:100%" class="flex flex-v">
        <Spin size="large" fix v-if="submitting"></Spin>
        <header class="header">
            <a class="btn-back" @click="prev"><i class="icon icon-left"></i>返回</a>
            <a class="btn-save" v-if="isShowCategory" @click="getChecked"><i class="am-icon-save"></i>确定</a>
            <a class="btn-save" v-if="isView&&!isShowCategory" @click="handleSave"><i class="am-icon-save"></i>保存</a>
            <a class="btn-save" v-if="!isView" @click="handleNew"><i class="am-icon-plus"></i>添加</a>
            <h1 v-html="getTitle"></h1>
        </header>
        <div class="flex1" style="overflow:auto">
            <transition enter-active-class="anim fadeInRight" leave-active-class="anim fadeOutRight">
                <div class="page" v-show="!isView">
                    <pull ref="pull" @onpull="handlePull" :count="count">
                        <div class="input-search"><a class="am-icon-search" @click="handlePull"></a><input ref="keyword" type="text" placeholder="搜索" autocomplete="off" v-model="keyword"></div>
                        <ul class="list">
                            <li v-for="item in datas" :key="item.Id" @click="showInfo(item)"><i class="icon icon-right"></i>{{item.Remark}}</li>
                        </ul>
                    </pull>
                </div>
            </transition>
            <transition enter-active-class="anim fadeInRight" leave-active-class="anim fadeOutLeft">
                <div v-show="isView" class="flex1" style="overflow:auto">
                    <div v-show="isView" class="page">
                        <h3 v-if="item==null" class="am-text-center"><i class="am-icon-spinner am-icon-pulse am-margin-top-xl"></i> 正在加载...</h3>
                        <i-form ref="form" v-model="submitting" class="am-form-h" :action="submitUrl" @success="handleSuccess" v-else>
                            <input type="hidden" name="Id" />
                            <input type="hidden" name="productCount" :value="checkedProduct.length" />
                            <input type="hidden" name="State" v-model="orderStateModel" />
                            <form-item label="客户">
                                <i-select name="ClientId" :options="clientList"></i-select>
                            </form-item>
                            <form-item label="订单状态">
                                <RadioGroup v-model="orderStateModel">
                                    <Radio v-for="item in orderState" :label="item.text" :value="item.id">{{item.text}}</Radio>
                                </RadioGroup>
                            </form-item>
                            <form-item label="备注">
                                <input type="text" name="Remark" />
                            </form-item>
                            <form-item label="产品列表" id="plist">
                                <!--<Tree ref="showList" :data="productShowList" @on-check-change="checkProduct" show-checkbox multiple></Tree>-->
                                <!--<i-select :tree="true" placeholder="请选择..." v-model="selected" multiple transfer :options="productShowList" :on-change="onChange" ></i-select>-->
                                <button class="am-btn" @click="showCategory" type="button">产品分类</button>
                            </form-item>
                            <form-item class="am-cf am-margin-0" v-if="checkedProduct.length>0">
                                <div class="am-u-sm-3"><strong>价格</strong></div>
                                <div class="am-u-sm-3"><strong>数量</strong></div>
                                <div class="am-u-sm-3"><strong>折扣</strong></div>
                                <div class="am-u-sm-3"><strong>成交价</strong></div>
                            </form-item>
                            <template v-for="(item,index) in checkedProduct">
                                <form-item :label="item.parentName + item.text" class="order-list">
                                    <div class="am-cf am-u-sm-12">
                                        <div class="am-u-sm-3 am-padding-left-0">
                                            <input type="hidden" :name="'ParentId'+index" :value="item.parentId" />
                                            <input type="hidden" :name="'Id'+index" :value="item.id" />
                                            <input type="number" :name="'Price'+index" v-model="item.price" step="0.01" placeholder="价格" />
                                        </div>
                                        <div class="am-u-sm-3">
                                            <input type="number" :name="'Amount'+index" v-model="item.amount" placeholder="数量" />
                                        </div>
                                        <div class="am-u-sm-3 am-padding-right-0">
                                            <input type="text" :name="'Discount'+index" v-model="item.discount" placeholder="折扣" />
                                        </div>
                                        <div class="am-u-sm-3 am-padding-right-0">
                                            <input type="text" v-model="item.dealPrice" placeholder="成交价" />
                                        </div>
                                    </div>
                                </form-item>
                            </template>
                            <form-item class="am-cf am-text-right am-padding-bottom-xl" v-if="checkedProduct.length>0">
                                <strong class="am-padding-bottom-xl">订单合计：{{totalPrice}}元</strong>
                            </form-item>
                        </i-form>
                        <div v-if="isEdit" class="flex1 am-padding-left-xs am-padding-right-xs am-padding-bottom-xl am-margin-bottom-sm">
                            <button class="am-btn am-btn-danger am-btn-block am-radius" @click="delItem">删除</button>
                        </div>
                    </div>
                </div>        
            </transition>
            <div class="offcanvas" :class="isShowCategory?'show-menu':''">
                <div class="tab-main am-cf">
                    <div class="tab-search">
                        <div class="input-search">
                            <a class="am-icon-search"></a>
                            <input type="text" placeholder="搜索" autocomplete="off">
                        </div>
                    </div>
                    <div class="tab-nav am-fl">
                        <pull ref="orderPull" @onpull="handleOrderPull" :count="orderCount">
                            <ul class="am-padding-0">
                                <template v-for="(item,index) in productShowList">
                                    <li :class="productShowChildren==item.children?'active':''" @click="productShowChildren=item.children">
                                        <img :src="item.icon" />
                                        <span>{{item.text}}</span>
                                    </li>
                                </template>
                            </ul>
                        </pull>
                    </div>
                    <div class="tab-list am-fl">
                        <ul class="list p-list">
                            <li class="am-cf" v-for="sub in productShowChildren" @click="sub.Checked=!sub.Checked;">
                                <div class="am-fl chk">
                                    <Checkbox :key="sub.id" v-model="sub.Checked"></Checkbox>
                                </div>
                                <div class="am-fl">
                                    <p class="am-text-truncate">{{sub.spec}} {{sub.remark}}</p>
                                    <p class="sub"> {{sub.price}}元(参:{{sub.referencePrice}})/余:{{sub.amount}}</p>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="tab-close" @click="isShowCategory=false">
                    <span>点击此处关闭<i class="am-text-center am-icon-chevron-circle-left"></i></span>       
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    import pull from 'components/pull';
    import { getDatas, getInfo, rootUrl, del, getOrderState, getClientId, getProductTree} from 'api/erp';

    export default {
        components: { pull },
        data() {
            return {
                keyword: '',
                submitting: false,
                submitUrl: rootUrl + 'order/save',
                isView: false,
                item:null,
                datas: [],
                count: 0,
                isEdit: false,
                productShowList:[],
                productShowChildren:[],
                orderState:[],
                orderStateModel:null,
                clientList:[],
                checkedProduct:[], //选中的产品
                selected:null,
                orderKeyword:'',
                isShowCategory:false,
                orderCount:0
            }
        },
        computed: {
            getTitle() {
                if(this.isShowCategory)
                    return '选择产品类别';
                else if (this.isView) 
                    return '查看订单';
                return '订单列表';
            },
            totalPrice(){
                var t = 0;
                for(var i = 0; i < this.checkedProduct.length; i++){
                    var item = this.checkedProduct[i];
                    t = t + (item.price * item.amount) * item.discount;
                }
                return t.toFixed(2);
            }
        },
        watch: {
            keyword(val) {
                this.hanldeSearch();
            },
            orderKeyword(val){
                this.hanldeOrderSearch();
            }
        },
        methods: {
            hanldeSearch() {
                if (this.$timer) {
                    clearTimeout(this.$timer);
                    this.$timer = null;
                }
                let self = this;
                this.$timer = setTimeout(function() {
                    self.$timer = null;
                    self.handlePull();
                },500);
            },
            hanldeOrderSearch() {
                if (this.$orderTimer) {
                    clearTimeout(this.$orderTimer);
                    this.$orderTimer = null;
                }
                let self = this;
                this.$orderTimer = setTimeout(function() {
                    self.$orderTimer = null;
                    self.handleOrderPull();
                },500);
            },
            prev() {
                if(this.isView){
                    if(this.isShowCategory)
                        this.isShowCategory = false;
                    else{
                        this.item = null;
                        this.isView = false;
                        this.isEdit = false;
                        this.checkedProduct = [];
                    }
                }else
                    this.back();
            },
            async showInfo(item) {
                let result = await getInfo('order', item.Id);
                this.item = result.data;
                this.orderStateModel = this.item.State;
                this.isView = true;
                this.isEdit = true;
                console.log(result.data);
                this.getProducts(this.item.ProductIds);
                    
                this.$nextTick(function () {
                    this.$refs.form.fill(this.item);
                });
            },
            handleNew() {
                //this.getProducts();
                this.isView = true;
                this.item = {};
            },
            handleSave() {
                this.$refs.form.submit();
            },
            async loadData(page, cb) {
                try {
                    let result = await getDatas('order', page, this.keyword);
                    if (result.succ) {
                        if (page > 0)
                            this.datas = this.datas.concat(result.data.datas);
                        else
                            this.datas = result.data.datas;
                        if (cb) cb(result.data.haveMore);
                        this.count = result.data.count;
                    } else {
                        if (cb) cb(true);
                        this.count = 0;
                        this.$Message.error(result.data);
                    }

                } catch (error) {
                    console.log(error)
                }
            },
            handlePull(config) {
                if (!config) {
                    let self = this;
                    config = {page:this.$refs.pull.page, cb:function(haveMore) {
                        self.$refs.pull.loadMore = haveMore;
                    }};
                }
                this.loadData(config.page, config.cb);
            },
            handleSuccess() {
                this.$Message.success('保存成功！');
            },
            delItem(){
                var self = this;
                if(confirm("确认删除该数据？")){
                    let result = del('order', self.item.Id);
                    if(result){
                        self.loadData(0);
                        self.item = null;
                        self.isView = false;
                        self.isEdit = false;
                    }
                }
            },
            async getProducts(ids){
                let result = await getProductTree(ids);
                this.productShowList = result;
                console.log("edit:"+result);
                this.getChecked();
            },
            getChecked(){
                if(this.isShowCategory)
                    this.isShowCategory = false;
                this.checkedProduct = [];
                var self = this;
                var list = this.productShowList;
                console.log("list:", list);
                list.forEach((item) =>{
                    var children = item.children.filter(a => a.Checked);
                    console.log("children:", children.length);
                    children.forEach((sub) => {
                        console.log("sub:" + sub.id);
                        if(this.isEdit){
                            var order = self.item.Products.filter(a => a.ProductId == sub.id)[0];
                            console.log("order:" + order);
                            sub.price = order.Price;
                            sub.amount = order.Amount;
                            sub.remark = order.Remark;
                            sub.discount = order.Discount;
                        }
                        self.checkedProduct.push(sub);
                    });
                });
                console.log("selected product:", this.checkedProduct.length);
                setTimeout(function(){
                    $('.page').scrollTop($('.page').height() - 400); 
                },100);
            },
            handleSelectPro(){
                this.getChecked();
            },
            handleOrderPull(config){
                if (!config) {
                    let self = this;
                    config = {page:this.$refs.orderPull.page, cb:function(haveMore) {
                        self.$refs.orderPull.loadMore = haveMore;
                    }};
                }
                this.loadOrderData(config.page, config.cb);
            },
            async loadOrderData(page, cb) {
                try {
                    let result = await getDatas('ordercategory', page, this.orderKeyword);
                    console.log("Result:" + result);
                    if (result.succ) {
                        if (page > 0)
                            this.productShowList = this.productShowList.concat(result.data.datas);
                        else
                            this.productShowList = result.data.datas;
                        if(page == 0)
                            this.productShowChildren = this.productShowList[0].children;
                        if (cb) cb(result.data.haveMore);
                        this.orderCount = result.data.count;
                    } else {
                        if (cb) cb(true);
                        this.orderCount = 0;
                        this.$Message.error(result.data);
                    }

                } catch (error) {
                    console.log(error)
                }
            },
            showCategory(){
                this.isShowCategory = true;
                if(this.checkedProduct.length==0){
                    this.handleOrderPull()
                }
            }
        },
        async created() {
            let result = await getOrderState();
            this.orderState = result.data;
            let list = await getClientId();
            this.clientList = list.data;
            this.handlePull();
        }
    }
</script>
<style>
    html, body, .container { height:100%; overflow:hidden }
    #plist .dropdown-toggle{background:#fff}
    #plist .i-select .dropdown-toggle{height:auto}
    .ivu-modal-body{position: relative;}
    .ivu-modal-body .page{padding:0!important;}
    .ivu-modal-body .list li{padding:8px 0px 8px 20px}
</style>
